// pages/indexDetail/indexDetail.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    _id: "",
    detail: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(options);
    this.setData({
      _id: options._id
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // 创建动画实例
    this.animation = wx.createAnimation({
      timingFunction: "ease"
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getDetail();
  },

  // 获取详情数据
  getDetail() {
    let url = "/product/detail";
    let data = {
      _id: this.data._id
    }
    app.$http.get(url, data).then(res => {
      // console.log("商品详情", res);
      this.setData({
        detail: res.detail
      })
    })
  },

  // 加入购物车
  addCart() {
    // 1、向后台提交
    let url = "/cart/add";
    let data = {
      _id: this.data._id
    }
    app.$http.post(url, data, true).then(res => {
      // 2、购物车数字加1
      let cartNum = this.data.detail.cartNum + 1;
      this.setData({
        detail: {
          ...this.data.detail,
          cartNum
        }
      })

      // 3、动画平移
      this.animation.translate(-360 / 750 * wx.getSystemInfoSync().windowWidth, 0).step().opacity(0, 0).step().translate(0, 0).step().opacity(1, 0).step()
      this.setData({ animation: this.animation.export() })

      console.log("添加到购物车", res);
      wx.showToast({
        title: '加入成功',
        icon: 'success',
        duration: 2000
      })
    })
  },

  // 立即购买
  buy() {
    let url = '/user/checkToken';
    app.$http.get(url).then(res => {
      if (res.code === 666) {
        let detail = this.data.detail;
        detail.buyNum = 1;
        let orderData = {
          goodsList: [detail],
          totalMoney: this.data.detail.price / 100
        }
        let orderDataStr = JSON.stringify(orderData)
        wx.navigateTo({
          url: `/pages/confirmOrder/confirmOrder?orderDataStr=${orderDataStr}`
        })
      }
    })
  }

})